package cn.time1024.time_app.ui.notebook

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.timeassistant.network.ApiService
import cn.time1024.time_app.R

class NotebookAdapter(
    private val onEdit: (ApiService.NoteItem) -> Unit,
    private val onDelete: (ApiService.NoteItem) -> Unit
) : RecyclerView.Adapter<NotebookAdapter.VH>() {

    private val items = mutableListOf<ApiService.NoteItem>()

    class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
        val tvContent: TextView = itemView.findViewById(R.id.tvContent)
        val btnEdit: View = itemView.findViewById(R.id.btnEdit)
        val btnDelete: View = itemView.findViewById(R.id.btnDelete)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_note, parent, false)
        return VH(v)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: VH, position: Int) {
        val item = items[position]
        holder.tvTitle.text = item.title ?: ""
        holder.tvContent.text = item.content ?: ""
        holder.btnEdit.setOnClickListener { onEdit(item) }
        holder.btnDelete.setOnClickListener { onDelete(item) }
    }

    fun replaceAll(list: List<ApiService.NoteItem>) {
        items.clear(); items.addAll(list); notifyDataSetChanged()
    }

    fun appendAll(list: List<ApiService.NoteItem>) {
        val start = items.size; items.addAll(list); notifyItemRangeInserted(start, list.size)
    }
}

